package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单定时处理
 * 1. 超时未支付
 * 2. 已完成一直处在派送中
 */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    OrderMapper orderMapper;

    /**
     * 1. 超时未支付
     */
    @Scheduled(cron = "0 * * * * ? ")//每分钟
    public void handleOutTimeUnPayOrders() {
        log.info("处理，超时订单");
        // 待付款 超时
        LocalDateTime outTimeOrders = LocalDateTime.now().minusMinutes(15);
        List<Orders> ordersList = orderMapper.getStatusAndOrderTime(Orders.PENDING_PAYMENT,outTimeOrders);

        // 修改订单状态
        if(ordersList!=null && ordersList.size()>0){
            for (Orders orders : ordersList) {
                orders.setCancelReason("订单超时，未支付");
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.updateStatusAndOrderTime(orders);
            }
        }
    }

    /**
     * 2. 已完成一直处在派送中
     */
    @Scheduled(cron = "0 0 3 * * ? ")// 凌晨三点处理
    public void ordersInDelivery(){
        log.info("处理，已完成一直处在派送中");
        // 派送中 小于 24：00：00
        LocalDateTime outTimeOrders = LocalDateTime.now().minusHours(3);
        List<Orders> ordersList = orderMapper.getStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS,outTimeOrders);

        // 修改订单状态
        if(ordersList!=null && ordersList.size()>0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.updateStatusAndOrderTime(orders);
            }
        }
    }

}
